//
//  NSDate+Component.m
//  年輕時代的睡神
//
//  Created by 劉裕 on 25/3/2016.
//  Copyright © 2016年 劉裕. All rights reserved.
//

#import "NSDate+Component.h"

@implementation NSDate (Component)

#pragma mark - 时间比较
- (NSString *)dateComponent {
    NSDateFormatter *format = [NSDateFormatter new];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar components:unit fromDate:self toDate:now options:0];
    if ([self isThisYear]) {
        if ([self isToday]) {
            if (cmps.hour >= 1) {
                return [NSString stringWithFormat:@"%ld小时前", (long)cmps.hour];
            } else if (cmps.minute >= 1) {
                return [NSString stringWithFormat:@"%ld分钟前", (long)cmps.minute];
            } else {
                return @"刚刚";
            }
        } else if ([self isYesterday]) {
            format.dateFormat = @"昨天 HH:mm";
            return [format stringFromDate:self];
        } else {
            format.dateFormat = @"MM-dd";
            return [format stringFromDate:self];
        }
    } else {
        format.dateFormat = @"yyyy-MM-dd";
        return [format stringFromDate:self];
    }
}

- (BOOL)isThisYear {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmps = [calendar components:NSCalendarUnitYear fromDate:self toDate:[NSDate date] options:0];
    return cmps.year == 0;
}
- (BOOL)isToday {
    NSDateFormatter *fmt = [NSDateFormatter new];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *dateStr = [fmt stringFromDate:self];
    NSString *nowStr = [fmt stringFromDate:[NSDate date]];
    return [dateStr isEqualToString:nowStr];
}
- (BOOL)isYesterday {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateFormatter *fmt = [NSDateFormatter new];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *dateStr = [fmt stringFromDate:self];
    NSString *nowStr = [fmt stringFromDate:[NSDate date]];
    NSDate *date = [fmt dateFromString:dateStr];
    NSDate *now = [fmt dateFromString:nowStr];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *cmps = [calendar components:unit fromDate:date toDate:now options:0];
    return cmps.year == 0 && cmps.month == 0 && cmps.day == 1;
}

@end
